//声明一个函数
function createStore(reducer) {
  //声明一个状态
  let state;
  //声明一个数组
  let cbs = [];

  //声明 getState  获取当前状态
  let getState = () => {
    return state;
  };

  //声明dispatch
  let dispatch = (action) => {
    //判断
    if(typeof action === 'object'){
      //通过调用 reducer 函数, 获得新的状态值
      let newState = reducer(state, action);
      //更新当前的状态值
      state = newState;
      //循环数组
      cbs.forEach(cb => {
        //调用回调函数
        cb();
      })
    }
    if(typeof action === 'function'){
      return action(dispatch);
    }
  };

  //声明subscribe 函数
  let subscribe = (cb) => {
    cbs.push(cb);
  }

  //初始化状态值
  dispatch({ type: "@@redux/INIT" });

  //返回值
  return {
    getState,
    dispatch,
    subscribe
  };
}

let store = createStore((state = 10, action) => {
  switch (action.type) {
    case "add":
      return state + action.payload;
    case "sub":
      return state - action.payload;
    default:
      return state;
  }
});

//订阅回调函数
store.subscribe(() => {
  console.log('状态更新啦~~11');
});

store.subscribe(() => {
  console.log('状态更新啦~~22');
});

//获取状态值
// console.log(store.getState());

//更新状态
store.dispatch({ type: "add", payload: 1 });
// store.dispatch({ type: "sub", payload: 3 });
// console.log(store.getState());
